package com.flycms.modules.statistics.controller.front;


import com.flycms.common.utils.SessionUtils;
import com.flycms.common.utils.StrUtils;
import com.flycms.common.utils.ip.IpUtils;
import com.flycms.common.utils.spring.SpringContextUtil;
import com.flycms.framework.web.controller.BaseController;
import com.flycms.framework.web.domain.AjaxResult;
import com.flycms.modules.statistics.domain.StatisticsAccessRecord;
import com.flycms.modules.statistics.service.IStatisticsAccessRecordService;
import com.flycms.modules.data.domain.dto.IpAddressDTO;
import com.flycms.modules.data.service.IIpAddressService;
import com.flycms.modules.user.domain.User;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 访问记录Controller
 * 
 * @author admin
 * @date 2020-12-09
 */
@Controller
public class StatisticsAccessRecordController extends BaseController
{
    @Autowired
    private IStatisticsAccessRecordService statisticsAccessRecordService;

    @Autowired
    private IIpAddressService ipAddressService;

    /**
     * 访问来源(1:PC 2:移动端H5 3:微信客户端H5 4:IOS 5:安卓 6:小程序)
     */
    public static final Short ACCESS_TYPE_PC = 1;
    public static final Short ACCESS_TYPE_MOBILE_H5 = 2;
    public static final Short ACCESS_TYPE_WECHAT_H5 = 3;
    public static final Short ACCESS_TYPE_IOS = 4;
    public static final Short ACCESS_TYPE_ANDROID = 5;
    public static final Short ACCESS_TYPE_SMALL_PROGRAM = 6;

    /**来源网站类型 （1-搜索引擎 2-外部链接 3-直接访问）**/
    public static Integer RESOURCE_SEARCHER = 1;
    public static Integer RESOURCE_EXT = 2;
    public static Integer RESOURCE_SELF = 3;

    /**访客设备系统（如：Win10 Mac10 Android8）**/
    public static final String DEVICE_WINDOWS_10 = "Windows10";
    public static final String DEVICE_WINDOWS_8 = "Windows8";
    public static final String DEVICE_WINDOWS_7 = "Windows7";
    public static final String DEVICE_IPHONE_12 = "iPhone12";
    public static final String DEVICE_IPHONE_11 = "iPhone11";
    public static final String DEVICE_IPHONE_10 = "iPhone10";
    public static final String DEVICE_ANDROID_8  = "Android8";
    public static final String DEVICE_ANDROID_7  = "Android7";
    public static final String DEVICE_ANDROID_6  = "Android6";
    public static final String DEVICE_MAC = "Mac";
    public static final String OTHERS = "Others";

    /**计算机设备**/
    public static final Short COMPUTER = 1;
    /**移动设备**/
    public static final Short MOBIE = 2;

    /**浏览器类型**/
    public static final String BROWSER_EDGE = "Edge";
    public static final String BROWSER_SAFARI = "Safari";
    public static final String BROWSER_CHROME = "Chrome";
    public static final String BROWSER_FIREFOX = "Firefox";
    /////////////////////////////////
    ///////       增加       ////////
    /////////////////////////////////

    /**
     * 新增访问记录
     */
    @ResponseBody
    @GetMapping(value = "/statistics/record")
    public AjaxResult add(HttpServletRequest request, @RequestParam(value = "sourceUrl", required = false) String sourceUrl,
                          @RequestParam(value = "accessUrl", required = false) String accessUrl)
    {
        //System.out.println(request.getRequestURI()+"---------------"+request.getHeader("referer"));
        if(request.getHeader("referer") == null){
            return AjaxResult.error("请勿非法提交数据！");
        }

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));  //WINDOWS-CHROME
        //获取浏览器信息
        //Browser browser = userAgent.getBrowser();
        //获取浏览器版本
        //Version version = userAgent.getBrowserVersion();
        //获取浏览器所有语言
        String languages = request.getHeader("Accept-Language");
        //获取操作系统
        OperatingSystem os = userAgent.getOperatingSystem();    //WINDOWS
        //获取ip地址
        String ip = IpUtils.getIpAddr(request);
        if("127.0.0.1".equals(ip)){
            return AjaxResult.error("本机不记录");
        }
        String jsessionid = request.getSession().getId();
        StatisticsAccessRecord record = new StatisticsAccessRecord();
        record.setCookieId(jsessionid);
        record.setAccessDevice(os.getName());
        //setAccessBrowser(browser.getName()+ " "+version);
        //来源网站
        //String sourceUrl = request.getHeader("Origin");
        record.setSourceUrl(sourceUrl);
        //访问网站(点击链接才可获取)
        //String accessUrl = request.getHeader("referer");
        record.setAccessUrl(accessUrl);
        User user = SessionUtils.getUser();
        if(user != null){
            record.setIsLogin(false);
            String loginName = null;
            if(!StrUtils.isEmpty(user.getNickname())){
                loginName = user.getNickname();
            }else if(!StrUtils.isEmpty(user.getUsername())){
                loginName = user.getUsername();
            }else if(!StrUtils.isEmpty(user.getMobile())){
                loginName = user.getMobile();
            }else if(!StrUtils.isEmpty(user.getEmail())){
                loginName = user.getEmail();
            }
            record.setLoginUserName(loginName);
        }else{
            record.setIsLogin(true);
        }
        this.device(request,record);
        this.browser(request,record);
        record.setAccessIp(ip);
        if(StrUtils.isboolIp(ip)){
            IpAddressDTO address=ipAddressService.findSearchIpAddress(ip);
            if(address != null){
                if(!StrUtils.isEmpty(address.getProvince())){
                    record.setAccessProvince(address.getProvince());
                }
                if(!StrUtils.isEmpty(address.getCity())){
                    record.setAccessCity(address.getCity());
                }
                if(!StrUtils.isEmpty(address.getCounty())){
                    record.setAccessCountry(address.getCounty());
                }
            }

        }
        //访问来源客户端类型
        Short accessType = SpringContextUtil.isMobile() || SpringContextUtil.isTablet()
                ? ACCESS_TYPE_MOBILE_H5
                : SpringContextUtil.isPc()
                ? ACCESS_TYPE_PC
                : SpringContextUtil.isWxH5()
                ? ACCESS_TYPE_WECHAT_H5
                : null;
        record.setAccessSourceClient(accessType);
        record.setEngineName(engineName(sourceUrl));
        if(!StrUtils.isEmpty(sourceUrl)){
            if(StrUtils.getTopDomain(sourceUrl)!=null){
                record.setSourceDomain(StrUtils.getTopDomain(sourceUrl));
            }
        }

        int conut=statisticsAccessRecordService.insertStatisticsAccessRecord(record);
        if(conut>0){
            //SessionUtils.setUser(user);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 访客设备系统
     *
     * @param request 请求
     * @param record  设备对象
     * @Title: device
     */
    protected StatisticsAccessRecord device(HttpServletRequest request, StatisticsAccessRecord record) {
        // 分析浏览器UserAgent,得到设备信息
        String userAgent = request.getHeader("User-Agent");
        if (!StringUtils.isNotBlank(userAgent)) {
            record.setAccessDevice(OTHERS);
            record.setDeviceType(MOBIE);
        }
        //Windows 10,8,7版本
        if (userAgent.contains("Windows NT 10.0")) {
            record.setAccessDevice(DEVICE_WINDOWS_10);
            record.setDeviceType(COMPUTER);
        } else if (userAgent.contains("Windows NT 6.2")) {
            record.setAccessDevice(DEVICE_WINDOWS_8);
            record.setDeviceType(COMPUTER);
        } else if (userAgent.contains("Windows NT 6.1")) {
            record.setAccessDevice(DEVICE_WINDOWS_7);
            record.setDeviceType(COMPUTER);
        } else if (userAgent.contains("iPhone OS 12")) {
            //苹果12,11,10
            record.setAccessDevice(DEVICE_IPHONE_12);
            record.setDeviceType(MOBIE);
        } else if (userAgent.contains("iPhone OS 11")) {
            record.setAccessDevice(DEVICE_IPHONE_11);
            record.setDeviceType(MOBIE);
        } else if (userAgent.contains("iPhone OS 10")) {
            record.setAccessDevice(DEVICE_IPHONE_10);
            record.setDeviceType(MOBIE);
        } else if (userAgent.contains("Android 8")) {
            //安卓8,7,6
            record.setAccessDevice(DEVICE_ANDROID_8);
            record.setDeviceType(MOBIE);
        } else if (userAgent.contains("Android 7")) {
            record.setAccessDevice(DEVICE_ANDROID_7);
            record.setDeviceType(MOBIE);
        } else if (userAgent.contains("Android 6")) {
            record.setAccessDevice(DEVICE_ANDROID_6);
            record.setDeviceType(MOBIE);
        } else if (userAgent.contains(DEVICE_MAC)) {
            record.setAccessDevice(DEVICE_MAC);
            record.setDeviceType(MOBIE);
        } else {
            record.setAccessDevice(OTHERS);
            record.setDeviceType(MOBIE);
        }
        return record;
    }

    /**
     * 浏览器
     *
     * @param request 请求
     * @param record  设备对象
     * @Title: browser
     */
    protected StatisticsAccessRecord browser(HttpServletRequest request, StatisticsAccessRecord record) {
        // 分析浏览器UserAgent,得到设备信息
        String userAgent = request.getHeader("User-Agent");
        // 分析浏览器UserAgent,得到设备信息
        UserAgent agent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));  //WINDOWS-CHROME
        //获取浏览器版本
        Version version = agent.getBrowserVersion();
        if (userAgent.contains(BROWSER_CHROME)) {
            record.setAccessBrowser(BROWSER_CHROME+" "+version);
        } else if (userAgent.contains(BROWSER_FIREFOX)) {
            record.setAccessBrowser(BROWSER_FIREFOX+" "+version);
        } else if (userAgent.contains(BROWSER_EDGE)) {
            record.setAccessBrowser(BROWSER_EDGE+" "+version);
        } else if (userAgent.contains(BROWSER_SAFARI) && userAgent.contains("version")) {
            record.setAccessBrowser(BROWSER_SAFARI+" "+version);
        } else {
            record.setAccessBrowser(OTHERS+" "+version);
        }
        return record;
    }

    /**
     * 搜索引擎名称
     **/
    protected String engineName(String url) {
        if (!StringUtils.isNotBlank(url)) {
            return "其他";
        }
        if (url.equalsIgnoreCase(Web.BAIDU.getUrl())) {
            return "百度搜索";
        } else if (url.equalsIgnoreCase(Web.SO.getUrl())) {
            return "360搜索";
        } else if (url.equalsIgnoreCase(Web.SOGOU.getUrl())) {
            return "搜狗搜索";
        } else if (url.equalsIgnoreCase(Web.CHINASO.getUrl())) {
            return "中国搜索";
        } else if (url.equalsIgnoreCase(Web.BING.getUrl())) {
            return "微软搜索";
        } else if (url.equalsIgnoreCase(Web.YAHOO.getUrl())) {
            return "雅虎搜索";
        } else if (url.equalsIgnoreCase(Web.GOOGLE.getUrl())) {
            return "谷歌搜索";
        } else {
            return "其他";
        }
    }

    public enum Web {
        BAIDU("https://www.baidu.com"),
        SO("https://www.so.com"),
        SOGOU("https://www.sogou.com"),
        BING("https://cn.bing.com"),
        YAHOO("https://search.yahoo.com"),
        GOOGLE("https://www.google.com"),
        CHINASO("http://www.chinaso.com"),
        ;

        Web(String url) {
            this.url = url;
        }

        private String url;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public static List<String> get() {
            return Arrays.asList(BAIDU.getUrl(), SO.getUrl(), SOGOU.getUrl(),
                    BING.getUrl(), YAHOO.getUrl(), GOOGLE.getUrl(), CHINASO.getUrl());
        }
    }

}
